﻿using System.Collections.Generic;
using UnityEngine;

public class RoadPath
{
    class RoadCore
    {
        public Vector3 m_Pos = new Vector3();
        public float m_fLenght; // 到这个点的距离
        public float m_Distance = 0;
        public Vector3 m_Dir = new Vector3();
        public Vector3 GetPos(float fDis)
        {
            return m_Pos + m_Dir * (fDis / m_fLenght);
        }
    }
    // 组成路点集合
    List<RoadCore> m_PathData = new List<RoadCore>();
    public void AddCore(Vector3 pos)
    {
        var core = new RoadCore();
        core.m_Pos = pos;
        core.m_fLenght = 0;
        core.m_Distance = 0;

        m_PathData.Add(core);

    }
    public void DoInit()
    {
        if (m_PathData.Count < 2)
        {
            XKLog.LogError("曲线路径初始化失败");
            return;
        }
        var pos = m_PathData[0];
        float fDis = 0;
        for (int i = 1; i < m_PathData.Count; ++i)
        {
            var cur = m_PathData[i];
            pos.m_Dir = cur.m_Pos - pos.m_Pos;
            cur.m_fLenght = Vector3.Distance(cur.m_Pos, pos.m_Pos);
            fDis += cur.m_fLenght;
            cur.m_Distance = fDis;
            pos = cur;
        }

    }

    public Vector3 GetPos(float fDis, ref bool bOver)
    {
        for (int i = m_PathData.Count - 1; i > 0; --i)
        {
            // 如果是最后一个点，
            if (i == m_PathData.Count - 1)
            {
                if (fDis >= m_PathData[i - 1].m_Distance)
                {
                    bOver = true;
                    return m_PathData[i - 1].m_Pos;
                }
                continue;
            }
            // 找到这个点最近的点
            var last = m_PathData[i];
            if (last.m_Distance < fDis)
            {
                var next = m_PathData[i + 1];
                return m_PathData[i].GetPos(fDis - last.m_Distance);
            }
        }
        return m_PathData[0].m_Pos;
    }
}
